package org.yunai.swjg.server.module.quest;

import org.slf4j.Logger;
import org.springframework.stereotype.Service;
import org.yunai.swjg.server.core.service.Online;
import org.yunai.swjg.server.module.quest.template.QuestTemplate;
import org.yunai.yfserver.common.LoggerFactory;
import org.yunai.yfserver.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 任务Service
 * User: yunai
 * Date: 13-5-8
 * Time: 下午11:42
 */
@Service
public class QuestService {

    private static final Logger LOGGER_GAME = LoggerFactory.getLogger(LoggerFactory.Logger.game, QuestService.class);

    private Map<Integer, AbstractQuest> quests;

    @PostConstruct
    public void init() {
        Map<Integer, QuestTemplate> templates = QuestTemplate.getAll();
        quests = new HashMap<>(templates.size());
        for (QuestTemplate template : templates.values()) {
            quests.put(template.getId(), AbstractQuest.Factory.create(template));
        }
        // 拼接前置/后置quest
        for (AbstractQuest quest : quests.values()) {
            int[] preQuestIds = StringUtils.splitInt(quest.getTemplate().getPreQuests(), "\\|");
            for (int preQuestId : preQuestIds) {
                AbstractQuest preQuest = quests.get(preQuestId);
                quest.addPreQuest(preQuest);
                preQuest.addNextQuest(quest);
            }
        }
    }

    /**
     * @param questId 任务编号
     * @return 任务逻辑对象
     */
    public AbstractQuest getQuest(Integer questId) {
        return quests.get(questId);
    }

    /**
     * @return 所有任务逻辑对象
     */
    public Collection<AbstractQuest> getAllQuest() {
        return quests.values();
    }

    /**
     * 接受任务
     *
     * @param online 在线信息
     * @param questId 任务编号
     */
    public void accept(Online online, Integer questId) {
        AbstractQuest quest = quests.get(questId);
        if (quest == null) {
            return;
        }
        quest.accept(online.getPlayer());
    }

    /**
     * 取消任务
     *
     * @param online 在线信息
     * @param questId 任务编号
     */
    public void cancel(Online online, Integer questId) {
        AbstractQuest quest = quests.get(questId);
        if (quest == null) {
            return;
        }
        quest.cancel(online.getPlayer());
    }

    /**
     * 完成任务
     *
     * @param online 在线信息
     * @param questId 任务编号
     */
    public void finish(Online online, Integer questId) {
        AbstractQuest quest = quests.get(questId);
        if (quest == null) {
            return;
        }
        quest.finish(online.getPlayer());
    }
}
